﻿using Furion.DatabaseAccessor;
using iWare.Wms.WorkerService.ThirdDB;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yitter.IdGenerator;

namespace iWare.Wms.WorkerService
{
    public class MaterialERP : BackgroundService
    {
        private readonly ILogger<MaterialERP> _logger;
        // 服务工厂
        private readonly IServiceScopeFactory _scopeFactory;

        public MaterialERP(ILogger<MaterialERP> logger,
                      IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        // 启动
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }

        // 执行逻辑
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                //定时同步物料信息
                //await AddMaterial();

                await Task.Delay(24 * 60 * 60 * 1000, stoppingToken);
            }
        }

        #region 定时同步物料信息
        /// <summary>
        /// 定时同步物料信息
        /// </summary>
        /// <returns></returns>
        public async Task AddMaterial()
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;
                var respository = Db.GetSqlRepository<ERPDbContextLocator>();

                //获取仓储实体
                var _wareMaterialRep = Db.GetRepository<WareMaterial>(services);

                var whereTime = DateTime.Now.ToString("yyyyMM");
                var whereTime1 = DateTime.Now.AddMonths(-1).ToString("yyyyMM");

                //查询近两个月的物料信息
                var materialList = await respository
                .SqlQueryAsync<MaterialErpInput>
                 (@"select MB001, --品号
	                       MB002, --品名
	                       MB003, --规格
	                       MB004, --库存单位
	                       MB009, --商品描述
	                       MB043, --检验方式 0:免检、1:抽检(减量)、2:抽检(正常)、3:抽检(加严)、4:全检
                           MB064, --库存数量
                           UDF07  --品牌名称
                    from INVMB where CREATE_DATE like '" + whereTime + "%' or CREATE_DATE like '" + whereTime1 + "%' ");

                List<WareMaterial> addMaterialList = new List<WareMaterial>();

                foreach (var item in materialList)
                {
                    var isExists = await _wareMaterialRep
                        .AnyAsync(u => u.Code.Equals(item.MB001) && u.Name.Equals(item.MB002));

                    //不存在执行新增操作
                    if (!isExists)
                    {
                        //抽检方式
                        var inspectionMethod = InspectionMethodEnum.mianjian;
                        if (item.MB043.Equals(0)) inspectionMethod = InspectionMethodEnum.mianjian;
                        else if (item.MB043.Equals(1)) inspectionMethod = InspectionMethodEnum.choujian_jianliang;
                        else if (item.MB043.Equals(2)) inspectionMethod = InspectionMethodEnum.choujian_zhengchang;
                        else if (item.MB043.Equals(3)) inspectionMethod = InspectionMethodEnum.choujian_jiayan;
                        else inspectionMethod = InspectionMethodEnum.quanjian;

                        var addMaterialModel = new WareMaterial
                        {
                            Id = YitIdHelper.NextId(),
                            Code = item.MB001 == null ? "" : item.MB001.Trim(),
                            Name = item.MB002 == null ? "" : item.MB002.Trim(),
                            SpecificationModel = item.MB003 == null ? "" : item.MB003.Trim(),
                            Unit = item.MB004 == null ? "" : item.MB004.Trim(),
                            Describe = item.MB009 == null ? "" : item.MB009.Trim(),
                            InspectionMethod = inspectionMethod,
                            Quantity = item.MB064,
                            BrandName = item.UDF07,
                            SupplerCode = "",
                            IsJiaJi = YesOrNot.N,
                            CreatedUserName = "LES SYSTEM",
                            CreatedTime = DateTimeOffset.Now
                        };
                        addMaterialList.Add(addMaterialModel);
                    }
                }
                // 批量新增
                await _wareMaterialRep.InsertNowAsync(addMaterialList);
                Console.WriteLine("定时同步物料信息");
            }
        }
        #endregion

        #region 定时更新加急件对应的正式采购单号
        /// <summary>
        /// 定时更新加急件对应的正式采购单号
        /// </summary>
        /// <returns></returns>
        [HttpPost("EditJiaJiJian")]
        public async Task EditJiaJiJian()
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;

                // 定义ERP仓储
                var erpRespository = Db.GetSqlRepository<ERPDbContextLocator>();

                // 定义送货单仓储
                var _goodsDeliveryRespository = Db.GetRepository<GoodsDelivery>();

                // 定义采购单仓储
                var _purchaseOrderRespository = Db.GetRepository<PurchaseOrder>();

                var whereTime = DateTime.Now.AddMonths(-3).ToString("yyyyMMdd");
                // 查询所有的ERP采购单表头是加急件的信息
                var purtcOutputList = await erpRespository
                    .SqlQueryAsync<PURTCOutput>
                    (@"select TC001, --采购单别
                              TC002, --采购单号
                              TC003, --采购日期
                              TC004, --供应商
                              TC009, --备注
                              TC011, --采购人员
                              TC023, --数量合计
                              TC047, --项目编号
                              UDF01, --收货地址
                              TC030, --签核状态码  0.待处理、S.传送中、1.签核中、2.退件、3.已核准、4.撤销审核中、5.作废中、6.取消作废中、N.不运行电子签核
                              TCD01  --是否结束 N:未结束、Y:结束 [DEF:""N""]
                       from PURTC where TCD01 = 'N' and TC030 = '3' and TC023 > 0 and TC003>'" + whereTime + "' and TC009 like '%加急件%' order by TC003 desc");

                // 查询所有的送货单是加急件的信息
                var purchaseOrderList = await _purchaseOrderRespository.DetachedEntities.Where(z => z.IsJiaJiJian == YesOrNot.Y && z.PurchaseNo.Length > 11).ToListAsync();
                foreach (var goodsItem in purtcOutputList)
                {
                    var purchaseOrder = purchaseOrderList.FirstOrDefault(z => z.SupplierInfoCode == goodsItem.TC004 && z.ProjectCode == goodsItem.TC047
                    && z.PurchaseNumber == goodsItem.TC023);
                    if (purchaseOrder != null)
                    {
                        // 更新加急件采购单的采购单号为正式采购单号
                        purchaseOrder.PurchaseNo = goodsItem.TC002;
                        await _purchaseOrderRespository.UpdateAsync(purchaseOrder);

                        // 查询送货单
                        var goodsDelivery = await _goodsDeliveryRespository.FirstOrDefaultAsync(z => z.SuppCode == goodsItem.TC004 && z.ProjectCode == goodsItem.TC047
                        && z.DeliveryQuantityTotal == goodsItem.TC023);

                        // 更新加急件送货单号的采购单号为正式采购单号
                        goodsDelivery.PurchaseNo = goodsItem.TC002;
                        await _goodsDeliveryRespository.UpdateAsync(goodsDelivery);
                    }
                }
            }

            #region 以前的代码
            //using (var scope = _scopeFactory.CreateScope())
            //{
            //    var services = scope.ServiceProvider;
            //    var respository = Db.GetSqlRepository<ERPDbContextLocator>();

            //    //获取实体仓储
            //    var _purchaseOrderRep = Db.GetRepository<PurchaseOrder>(services);

            //    // step1 查询LES系统所有未同步正式采购单号的数据
            //    var purchaseOrderList = await _purchaseOrderRep.DetachedEntities.Where(z => z.IsJiaJiJian == YesOrNot.Y && z.PurchaseNo.Length > 11).ToListAsync();

            //    // step2 查询ERP系统备注为加急件的采购主表信息
            //    var purtcOutputList = await respository
            //        .SqlQueryAsync<PURTCOutput>
            //        (@"select TC001, --采购单别
            //               TC002, --采购单号
            //               TC003, --采购日期
            //               TC004, --供应商
            //               TC009, --备注
            //               TC011, --采购人员
            //               TC023, --数量合计
            //               TC047, --项目编号
            //               UDF01, --收货地址
            //               TC030, --签核状态码  0.待处理、S.传送中、1.签核中、2.退件、3.已核准、4.撤销审核中、5.作废中、6.取消作废中、N.不运行电子签核
            //                  TCD01  --是否结束 N:未结束、Y:结束 [DEF:""N""]
            //           from PURTC where TCD01 = 'N' and TC030 = '3' and TC023 > 0 and TC009 like '%加急件%' order by TC003 desc");

            //    //查询LES系统是否存在ERP加急件
            //    foreach (var item in purtcOutputList)
            //    {
            //        //查询ERP采购单明细
            //        var pURTDOutputs = await respository
            //    .SqlQueryAsync<PURTDOutput>
            //    (@"select TD001, --采购单别
            //           TD002, --采购单号
            //           TD003, --序号
            //           TD004, --品号
            //           TD005, --品名
            //           TD006, --规格
            //           TD008, --采购数量
            //           TD009, --单位
            //           TD014, --备注
            //           TD022, --项目编号
            //           UDF03, --参数
            //              TD016, --N:未结束、Y:自动结束、y:指定结束
            //              TD018  --审核码
            //       from PURTD where TD018='Y' and TD002='" + item.TC002 + "' and TD001='" + item.TC001 + "' and TD022='" + item.TC047 + "'");

            //        // 查询送货单

            //        var purchaseOrder = purchaseOrderList.FirstOrDefault(u => u.PurchaseNo == item.TC002 && u.PurchaseType == item.TC001 && u.ProjectCode == item.TC047
            //        && item.TC023 == u.PurchaseNumber && u.Status != PurchaseStatusEnum.Delete);

            //        //更新加急件采购单号为正式采购单号
            //        if (purchaseOrder != null)
            //        {
            //            purchaseOrder.PurchaseNo = item.TC002;
            //            await _purchaseOrderRep.UpdateNowAsync(purchaseOrder);
            //        }
            //    }
            //}
            #endregion
        }
        #endregion

        // 停止
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}
